function join()
    setPlayerHudComponentVisible ( source, "health", false )
    setPlayerHudComponentVisible ( source, "clock", false )
	setPlayerHudComponentVisible ( source, "breath", false )
	setPlayerHudComponentVisible ( source, "armour", false )
	setPlayerHudComponentVisible ( source, "area_name", false )
	setPlayerHudComponentVisible ( source, "ammo", false )
	setPlayerHudComponentVisible ( source, "money", false )
	setPlayerHudComponentVisible ( source, "vehicle_name", false )
    setPlayerHudComponentVisible ( source, "wanted", false )
	setPlayerHudComponentVisible ( source, "weapon", false )
	setPlayerHudComponentVisible ( source, "radio", false )
	setPlayerNametagShowing ( source, false )
	showChat(source,false)
end
addEventHandler("onPlayerJoin", getRootElement(), join)

addEventHandler("onResourceStart", resourceRoot, function()
setFPSLimit(61)
setMinuteDuration(60000)
local time = getRealTime()
local h = time.hour
local m = time.minute
setTime(h,m)
end)

function savePlayerData(plr)
	local uid=getElementData(plr,"player:data").uid
	if not uid then return end
	local data = getElementData(plr,"player:data")
	if not data.logged then return end
	local skin=getElementModel(plr)
	local x,y,z = getElementPosition(plr)
	local position = ""..string.format("%.2f",x)..","..string.format("%.2f",y)..","..string.format("%.2f",z)..","..getElementInterior(plr)..","..getElementDimension(plr)..""
	local query=exports["cmta-db"]:dbSet("UPDATE cmta_users SET points=?, timeplayed=?, skin=?, level=?, exp=?, dailyclicks=?, PO=?, last_position=? WHERE id=?",
	data.points, data.timeplayed, skin, data.lvl, data.exp, data.dailyclicks, data.PO, position, data.uid)
	realTime=getRealTime()
	local r = realTime.year+1900
	local m = realTime.month+1
	local t = realTime.monthday
	local time=string.format("%04d-%02d-%02d %02d:%02d:%02d", r, m, t,realTime.hour, realTime.minute, realTime.second)
	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_users WHERE id=? LIMIT 1", data.uid)
	if result[1].premium <= time and data.vip then
	local data = getElementData(plr,"player:data")
	data.vip = false	
	setElementData(plr,"player:data",data)
	setPlayerName(plr,getPlayerName(plr):gsub("#%x%x%x%x%x%x",""))
	end
	local weapons = getAllPedWeapon(plr)
	if weapons then
		local weapons=exports["cmta-db"]:dbSet("UPDATE cmta_users SET weapons=? WHERE id=?",
		toJSON(weapons), data.uid)
	end
end

function save(plr)
	for i,v in ipairs(getElementsByType("player")) do
		if getElementData(v,"player:data") and getElementData(v,"player:data").logged then
			local data = getElementData(v,"player:data")
			data.timeplayed = data.timeplayed+1
			data.currentplaytime = data.currentplaytime+1
            setElementData(v,"player:data",data)
		    savePlayerData(v)
	    end
  	end
	end
setTimer(save,60000,0)

addEventHandler("onPlayerQuit", root, function() 
	if getElementData(source,"player:data").uid then
	exports["cmta-db"]:dbSet("update cmta_users set player_online=0 where id=?",getElementData(source,"player:data").uid)
	savePlayerData(source)
	end 
end)


function findPlayer(plr,cel)
	local target=nil
	if (tonumber(cel) ~= nil) then
		target=getElementByID("p"..cel)
	else -- podano fragment nicku
		for _,thePlayer in ipairs(getElementsByType("player")) do
			if string.find(string.gsub(getPlayerName(thePlayer):lower(),"#%x%x%x%x%x%x", ""), cel:lower(), 0, true) then
				if (target) then
					outputChatBox("Znaleziono wiecej niz jednego gracza o pasujacym nicku, podaj wiecej liter.", plr)
					return nil
				end
				target=thePlayer
			end
		end
	end
	if target and getElementData(target,"p:inv") then return nil end
	return target
end

local function findFreeValue(tablica_id)
	table.sort(tablica_id)
	local wolne_id=1
	for i,v in ipairs(tablica_id) do
		if (v==wolne_id) then wolne_id=wolne_id+1 end
		if (v>wolne_id) then return wolne_id end
	end
	return wolne_id
end

function assignPlayerID(plr)
	local gracze=getElementsByType("player")
	local tablica_id = {}
	for i,v in ipairs(gracze) do
		local lid=getElementData(v, "id")
		if (lid) then
			table.insert(tablica_id, tonumber(lid))
		end
	end
	local free_id=findFreeValue(tablica_id)
	if isElement(plr) then
	setElementData(plr,"id", free_id)
	setElementID(plr, "p" .. free_id)
	end
	return free_id
end

function getPlayerID(plr)
	if not plr then return "" end
	local id=getElementData(plr,"id")
	if (id) then
		return id
	else
		return assignPlayerID(plr)
	end
	
end

function getAllPedWeapon(plr)
    local weapons = { }
    for slot=1, 12 do
        local weapon = getPedWeapon(plr, slot)
        local ammo = getPedTotalAmmo(plr, slot)
        if (weapon > 0) and (ammo > 0) then
            weapons[weapon] = ammo
        end
    end
    return weapons
end

addEventHandler ("onPlayerJoin", getRootElement(), function()
	assignPlayerID(source)
end)

function sprawdzmute(plr,msg)
    if not wiadomosci[plr] then
        wiadomosci[plr] = {
            lastmessage = { },
            text = { },
            toggle = false,
            unmute = { },
			warnings = 0,
		}
    end
end


wiadomosci= {}

local function wtf(player)
if not player then return end
if isElement ( player ) then
	if not wiadomosci[player] then return end
	wiadomosci[player].text = nil; 
	wiadomosci[player].warnings = 0 
end 
end

local czas = 1*30*1000 --1 minuta

function sprawdzmute(plr,msg)
    if not wiadomosci[plr] then
        wiadomosci[plr] = {
            lastmessage = { },
            text = { },
            toggle = false,
            unmute = { },
			warnings = 0,
		}
    end
	if wiadomosci[plr].toggle then local pozostalyczas,_,_ = getTimerDetails(wiadomosci[plr].unmute); pozostalyczas = pozostalyczas/1000/60; wiadomosci[plr].warnings = wiadomosci[plr].warnings + 1 cancelEvent() return true end
	if wiadomosci[plr].warnings > 4 and not wiadomosci[plr].toggle then
					wiadomosci[plr].toggle = true
                    wiadomosci[plr].unmute = setTimer ( function ( player ) if isElement ( player ) then wiadomosci[player].toggle = false end end, czas, 1, plr )
					local pokazczas = czas/1000
					local tekst = ("#6400FF[Anty-SPAM] #808080Otrzymałeś wyciszenie na #ff000030 sekund#808080, za spam.")
                    outputChatBox(tekst, plr, 0, 170, 255,true)
            return true end
	if isTimer(wiadomosci[plr].lastmessage) then killTimer(wiadomosci[plr].lastmessage) end
   wiadomosci[plr].lastmessage = setTimer ( wtf, 10000, 1, plr )
   wiadomosci[plr].warnings = wiadomosci[plr].warnings + 1
   wiadomosci[plr].text = msg
   return false
end

function transfer(plr, cmd, target, value)
	if not target or not tonumber(value) then
        outputChatBox("#808080Wzór: #ff0000/przelej [nick/ID] [kwota]", plr,255,255,255,true)
        return
    end
	if getElementData(plr, "player:blokadaprzelej") then outputChatBox("Odczekaj chwilę przez kolejnym użyciem tej komendy!",plr,255,0,0) return end
	value=math.abs(value)
	local target=findPlayer(plr,target)
    if not target then
		outputChatBox("#ff0000Nie znaleziono podanego gracza.", plr,255,255,255,true)
        return
	end	
	if target == plr then return end
	if not getElementData(target, "player:data").uid then return end
    if getElementData(plr,"player:data").points < tonumber(value) then
		outputChatBox("#ff0000Nie posiadasz tylu punktów.", plr,255,255,255,true)
        return
    end		
    if tonumber(value) == 0 or tonumber(value) < 0 then return end
    if getElementData(plr,"player:data").lvl < 30 then
		outputChatBox("#ff0000Musisz posiadać 30 poziom, aby wysłać punkty.", plr,255,255,255,true)
    return
	end
    if getElementData(target,"player:data").lvl < 30 then
		outputChatBox("#ff0000Ten gracz musi posiadać 30 poziom, aby otrzymać punkty.", plr,255,255,255,true)
    return
	end	
    local data_plr = getElementData(plr,"player:data")
    local data_target = getElementData(target,"player:data")
	data_plr.points = data_plr.points-value
	data_target.points = data_target.points+value
    

	setElementData(plr,"player:data",data_plr)
	setElementData(target,"player:data",data_target)

	outputChatBox("#808080Pomyślnie przekazano graczowi #ccc000"..getPlayerName(target):gsub("#%x%x%x%x%x%x","").." #808080sumę #ff0000"..value.." pkt", plr, _, _, _, true)
	outputChatBox("#808080Otrzymano od gracza #ccc000"..getPlayerName(plr):gsub("#%x%x%x%x%x%x","").." #808080sumę #ff0000"..value.." pkt", target, _, _, _, true)
    triggerClientEvent(target,"transfer:sound",resourceRoot)
	setElementData(plr,"player:blokadaprzelej",true)
	setTimer(function()
		setElementData(plr,"player:blokadaprzelej",nil)
	end,30000,1)
end
addCommandHandler('przelej', transfer)

addEventHandler('onPlayerChat', root, function(msg, type)
	cancelEvent()
	if not getElementData(source,"player:data").uid then return end
	if type==1 then
		cancelEvent()
		local x,y,z=getElementPosition(source)
		local sphere=createColSphere(x,y,z, 100)
		local players=getElementsWithinColShape(sphere, 'player')
		destroyElement(sphere)
		for i,v in pairs(players) do
			outputChatBox(""..getPlayerName(source):gsub("#%x%x%x%x%x%x","").." "..msg:gsub("#%x%x%x%x%x%x",""), v, 0,206,209)
		end
	elseif type==0 then
		cancelEvent()
		if not isElement(source) then return end
		local x,y,z=getElementPosition(source)
		local sphere=createColSphere(x,y,z, 100)
		local players=getElementsWithinColShape(sphere, 'player')
	--[[	local result=exports["cmta-db"]:dbGet("SELECT * FROM cmta_punish WHERE type=? AND active=1 AND serial=? AND time>NOW() LIMIT 1","mute", getPlayerSerial(source))
		if result and #result > 0 then
			cancelEvent()
			outputChatBox("#808080Posiadasz wyciszenie na czacie do #ccc000"..result[1]["time"].."#808080 za #ccc000"..result[1]["reason"], source, 255, 0, 0,true)
			return
		else
			exports["cmta-db"]:dbSet("DELETE FROM cmta_punish WHERE type=? AND active=1 AND serial=?", "mute", getPlayerSerial(source))
			setElementData(source,"player:mute",false)
		end
	]]
	    for i,v in pairs(players) do
		local id=getElementData(source,"id")
		local level = tonumber(getElementData(source, "player:data").admin)
	    if level == 1 then
		cancelEvent()
		outputChatBox("#00FA9A[Moderator] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
	    elseif level == 2 then
		cancelEvent()
		outputChatBox("#6A5ACD[Super Moderator] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
		elseif level == 3 then
		cancelEvent()
		outputChatBox("#FF0000[Administrator] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
		elseif level == 4 then
		cancelEvent()
		outputChatBox("#C71585[Manager] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
		elseif getElementData(source,"player:data").vip then
		cancelEvent()
		outputChatBox("#FFFF00[V.I.P] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
		else
		cancelEvent()
		outputChatBox("#808080[Gracz] #FFFFFF"..getPlayerName(source):gsub("#%x%x%x%x%x%x","").."["..getElementData(source,"id").."]:#FFFFFF "..msg:gsub("#%x%x%x%x%x%x",""), v, _, _, _, true)
		end
		triggerClientEvent('cmta_admin:messageLog', root, ''..getPlayerName(source)..'['..getElementData(source, 'id')..'#c8c8c8]: '..msg:gsub("#%x%x%x%x%x%x",""))

	end
	destroyElement(sphere)
end
end)

addCommandHandler("v", function(plr, cmd, ...)
	if getElementData(plr,"player:data").vip then
	if not ... then
		local x = getElementData(plr,"player:pchatoff")
		if x == false then
		outputChatBox("#808080Pomyślnie wyłączono czat V.I.P.",plr, 255, 255, 255, true)
		setElementData(plr,"player:pchatoff",true)
		end
		if x == true then
		outputChatBox("#808080Pomyślnie włączono czat V.I.P.",plr, 255, 255, 255, true)
		setElementData(plr,"player:pchatoff",false)
		end
	return end
	if ... then
		local message = table.concat ( { ... }, " " )	
		if sprawdzmute(plr,message) then cancelEvent() return end
		if getElementData(plr,"player:data").mute then cancelEvent() return end
		local name = getPlayerName(plr):gsub("#%x%x%x%x%x%x","")
		for _,p in pairs(getElementsByType("player")) do
			if getElementData(p,"player:data").vip and not getElementData(p,"player:pchatoff") then
			outputChatBox("#FFFF00[V] #ffffff"..name.."["..(getElementData(plr,"id")).."]#ffff00: "..message:gsub("#%x%x%x%x%x%x",""), p, 255, 255, 255, true)
			end
		end
	end
end
end)

local function spawn(player)
	if player and isElement(player) then
		spawnPlayer(player,0,0,10)
		fadeCamera(player, true)
		setCameraTarget(player, player)
	end
end

addEventHandler("onPlayerWasted",root,function()
	local t = 5000
	setTimer(spawn,(t > 50 and t or 50),1,source)
end)

